package mall.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import mall.bean.User;
import mall.service.UserService;
import mall.service.impl.UserServiceImpl;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 防止一会获取参数时乱码
		req.setCharacterEncoding("UTF-8");
		// 获取参数
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		// 调用service
		User user = this.userService.login(username, password);
		// 准备响应结果
		Result result;
		if (user == null) {
			result = Result.error("用户名或密码错误");
		} else {
			result = Result.success();
		}
		// 返回结果给前端
		resp.setContentType("application/json;charset=UTF-8");
		resp.getWriter().append(JSON.toJSONString(result, true));
	}

}
